package com.nariano.webapp;

import java.util.List;
import java.util.Random;
import java.util.logging.Logger;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.nariano.server.domain.engine.Engine;
import com.nariano.server.domain.entities.Area;
import com.nariano.server.domain.entities.City;
import com.nariano.server.domain.entities.User;
import com.nariano.server.services.cityservice.CityService;
import com.nariano.server.services.mapservice.MapService;
import com.nariano.server.services.statistics.StatsService;
import com.nariano.server.services.userservice.UserService;

public class NarianoApp {
    
    static private Logger log = Logger.getLogger(NarianoApp.class.getCanonicalName());
    
    private int mapSize = 100;
    
    private boolean createCitiesDynamically;
    
    @Autowired
    @Qualifier(value="mapService")
    MapService mapService;
    
    @Autowired
    @Qualifier(value="userService")
    UserService userService;
    
    @Autowired
    @Qualifier(value="cityService")
    CityService cityService;
    
    @Autowired
    @Qualifier(value="engine")
    Engine engine;
    
    // Just to start it
    @Autowired
    @Qualifier(value="statsService")
    StatsService statsService;
    
    public void setMapSize(int size) {
		this.mapSize = size;
	}
    
	public void setCreateCitiesDynamically(boolean createCitiesDynamically) {
		this.createCitiesDynamically = createCitiesDynamically;
	}

	public void start(){
		
        if (mapService.getAreas().isEmpty()) {
            log.info("No map exists, create one");
            mapService.createMap(mapSize);
        }
        
        if (createCitiesDynamically) {
        	createCitiesDynamically();
        }
        // temp stop engine::: 
        engine.init();
        engine.start();
        
        MyShutdown sh = new MyShutdown();
        Runtime.getRuntime().addShutdownHook(sh);

    }

	private void createCitiesDynamically() {
		for(User u : userService.getAllUsers()) {
			
			if (cityService.getCities(u).size()>0) {
				continue;
			}
			
			List<Area> areas = mapService.getAreas();
	        Area aa = null;
	        Random rand = new Random();
	        for(int i=0;i<areas.size();i++) {
	            Area area = areas.get(rand.nextInt(areas.size()));
	            if (area.getCity()==null) {
	            	aa = area; 
	                break;
	            }
	        }
	        if (aa == null) throw new IllegalStateException("Failed to find area for city");
	        aa.setCity(new City(u.getUserName()+":"+u.getUserName(),u.getId(), aa.getLocation()));
	        mapService.updateAreas(aa);
		}
	}



	class MyShutdown extends Thread {
	    public void run() {
	    	// do nothing!
	    }
	}
}



